package com.guan.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.guan.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {
    private static final long CAPTCHA_TIME_OUT = 30 * 60 * 1000;

    @Autowired
    private CaptchaProperties captchaProperties;

    @RequestMapping("/getCaptcha")
    public void createCaptcha(HttpSession session, HttpServletResponse response) {
        try {
            LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
            String code = lineCaptcha.getCode();
            session.setAttribute(captchaProperties.getSession().getCode(), code);
            session.setAttribute(captchaProperties.getSession().getTime(), System.currentTimeMillis());
            System.out.println("生成验证码: " + code);
            response.setContentType("image/png");
            lineCaptcha.write(response.getOutputStream());
            response.getOutputStream().close();
        } catch (Exception e) {
            System.out.println("发生异常, e " + e);
        }

    }

    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session) {
        // 参数校验
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }
        // 验证码校验，正确，没超时
        String captchaCode = (String) session.getAttribute(captchaProperties.getSession().getCode());
        Long captchaTime = (Long) session.getAttribute(captchaProperties.getSession().getTime());
        if (!StringUtils.hasLength(captchaCode) || captchaTime == null
                || (System.currentTimeMillis() - captchaTime > CAPTCHA_TIME_OUT)) {
            return false;
        }
        if (captcha.equalsIgnoreCase(captchaCode)) {
            return true;
        }
        return false;
    }
}
